package framework

import (
	"fmt"
	"github.com/streadway/amqp"
	"zyb/config"
	"zyb/zybLog"
	"zyb/zybMQ"
	"zyb/zybMySQL"
	"zyb/zybPublic"
	"zyb/zybRedis"
)

type stContext struct {
	db  *zybMySQL.ZybMySQL
	mq  *zybMQ.RabbitMQ
	log *zybLog.ZybLog
	rds *zybRedis.ZybRedis
}

var (
	cfg = &config.Stcfg
	ctx stContext
)

func Init() bool {
	// init log.
	{
		ctx.log = new(zybLog.ZybLog)
		if !ctx.log.Init() {
			return false
		}
	}

	// init config.
	{
		xmlPath := "./config.xml"
		config.InitConfig(xmlPath)
		config.PrintConfig()
	}

	// init redis.
	{
		if config.IsInitRedis() {
			ctx.rds = zybRedis.New(cfg.RedisAddr,
				uint32(cfg.RedisPort),
				uint32(cfg.RedisDbNum))

			if !ctx.rds.Init() {
				ctx.log.Logger().Error("init redis error.")
				return false
			}
		}
	}

	// init rabbitmq.
	{
		ctx.mq = zybMQ.NewMQEx(cfg.ServerName,
			cfg.Url,
			onMessageEx)
	}

	// init mysql.
	{
		/*var (
			userName string = "mtp2"
			password string = "muchinfo"
			ip       string = "192.168.31.174"
			port     uint32 = 3307
			db       string = "mtp2"
			charset  string = "utf8"
		)*/

		ctx.db = zybMySQL.NewMySQLObject(cfg.DBUser,
			cfg.DBPwd,
			cfg.DBIp,
			cfg.DBUser, /*db = dbuser*/
			cfg.DBCharset,
			uint32(cfg.DBPort),
			logFunc)
		if !ctx.db.Init() {
			Log().Logger().Error("init mysql fail.")
			fmt.Println("init mysql fail.")
			return false
		}
	}

	return true
}

func MySQL() *zybMySQL.ZybMySQL {
	return ctx.db
}

func Mq() *zybMQ.RabbitMQ {
	return ctx.mq
}

func Log() *zybLog.ZybLog {
	return ctx.log
}

func Rds() *zybRedis.ZybRedis {
	return ctx.rds
}

func IsInitRedis() bool {
	return ctx.rds != nil
}

func Start() {
	if ctx.mq != nil {
		ctx.mq.Start()
	}
}

func Stop() {
	if ctx.mq != nil {
		ctx.mq.Stop()
	}
}

func logFunc(l zybPublic.LogLevel, strlog string) {

	if l.IsDebug() {
		Log().Logger().Debug(strlog)
	} else if l.IsInfo() {
		Log().Logger().Info(strlog)
	} else if l.IsError() {
		Log().Logger().Error(strlog)
	}
}

func onMessageEx(msg amqp.Delivery) {
	fCode := zybPublic.BytesToInt(msg.Body[:4])
	sid := zybPublic.BytesToInt(msg.Body[4:8])
	Log().Logger().Debugf("recv msg funcode[%d] sid[%d]\n", fCode, sid)
	_ = msg.Ack(true)
}
